package cn.strive.eams.repair.service.impl;

import cn.strive.eams.application.mapper.ApplicationMapper;
import cn.strive.eams.application.pojo.entity.Application;
import cn.strive.eams.base.enmus.ApplicationStatusEnum;
import cn.strive.eams.repair.pojo.dto.RepairSaveParam;
import cn.strive.eams.repair.pojo.entity.Repair;
import cn.strive.eams.repair.mapper.RepairMapper;
import cn.strive.eams.repair.service.RepairService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;

@Slf4j
@Service
public class RepairServiceImpl implements RepairService {
    @Autowired
    RepairMapper repairMapper;
    @Autowired
    ApplicationMapper applicationMapper;
    @Override
    public void saveRoomRepair(RepairSaveParam roomRepairSaveParam) {
        log.debug("保存维修业务需求:RoomRepairQuery={}", roomRepairSaveParam);
        Repair roomRepair = new Repair();
        BeanUtils.copyProperties(roomRepairSaveParam, roomRepair);
        roomRepair.setStatus(ApplicationStatusEnum.PENDING.getCode());
        roomRepair.setCreateTime(new Date());
        repairMapper.saveRepair(roomRepair);

        Application application = new Application();
        BeanUtils.copyProperties(roomRepairSaveParam, application);
        application.setApplyId(roomRepair.getId());
        application.setApplyNumber(generateApplyNumber());
        roomRepair.setStatus(ApplicationStatusEnum.PENDING.getCode());
        application.setCreateTime(new Date());
        log.debug("Application={}", application);
        applicationMapper.insert(application);
    }

    private String generateApplyNumber() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String currentDateStr = LocalDate.now().format(formatter);

        // 初始化四位数字部分，从0000开始
        int numberPart = 0;

        String applyNumber;
        do {
            String formattedNumber = String.format("%04d", numberPart);
            applyNumber = "APPLY" + currentDateStr + formattedNumber;

            // 检查是否有重复的昵称
            if (!isApplyNumberExists(applyNumber)) {
                break;
            }

            // 如果存在重复，则将数字部分增加10
            numberPart += 10;
        } while (true);

        return applyNumber;
    }

    private boolean isApplyNumberExists(String applyNumber) {
        return applicationMapper.existsByApplyNumber(applyNumber) > 0;
    }

}
